package com.houdoudou.customer.buy;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Car;
import com.houdoudou.bean.Customer;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.customer.FrgOrderOfActMain;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.me.SetPaySecretAct;
import com.houdoudou.customer.sqlite.CarDao;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public  class ChoosePayAct  extends Activity{



	TextView timeLeft,orderID,orderMoney,moneyAcount;
	TextView deduct;
	CheckBox ckHoudou,ckAli,ckTecent;
	Button confirm;
	LinearLayout lt_shadow;
	View.OnClickListener myClickListener;
	CompoundButton.OnCheckedChangeListener checkedListener;
	JSONObject orderJO;
	int payWay=-1;
	private static final String AFFAIR_ORDERPAID="orderPaid";
	private static final String AFFAIR_DeProtect="deProtectOrder";
	private static final int HOUDOUPAY=1,ALIPAY=2,TECENTPAY=3;
	public static String ACTION_ORDER_CHANGED="orderChanged";
	boolean isPaySuccess=false;
	public  Handler payResultHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
		
			switch (msg.what) {
			case HOUDOUPAY:{
			                	break;}

			default:{
				           break;}
			}
		}
		
	};;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_choose_pay);
		orderJO=JSONObject.fromObject(getIntent().getStringExtra("order"));
		initListener();
		timeLeft= (TextView) findViewById(R.id.tv_timeleft_act_choosepay);
		orderID=(TextView) findViewById(R.id.tv_orderid_act_choosepay);
		orderMoney= (TextView) findViewById(R.id.tv_moneycu_act_choosepay);
		moneyAcount= (TextView) findViewById(R.id.tv_moneyacount_act_choosepay);
		deduct=(TextView) findViewById(R.id.tv_moneydeduck_act_choosepay);
		ckHoudou= (CheckBox) findViewById(R.id.ck_houdoupay_act_choosepay);
		ckAli=(CheckBox) findViewById(R.id.ck_alipay_act_choosepay);
		ckTecent=(CheckBox) findViewById(R.id.ck_tecentpay_act_choosepay);
		lt_shadow=(LinearLayout) findViewById(R.id.lt_shadow_act_choosepay);
		
		confirm= (Button) findViewById(R.id.btn_confirm_act_choosepay);
		ckHoudou.setOnCheckedChangeListener(checkedListener);	
		ckAli.setOnCheckedChangeListener(checkedListener);	
		ckTecent.setOnCheckedChangeListener(checkedListener);	
	    confirm.setOnClickListener(myClickListener);
	    
	    orderID.setText(""+orderJO.getLong(Order.ID));
	    orderMoney.setText(""+orderJO.getDouble(Order.MONEYCU));
	    moneyAcount.setText(""+Constant.customerJO.getDouble(Customer.MONEY));
	    
	    deduct.setVisibility(View.GONE);
	}

	private void initListener(){
		
		myClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println(" payWay="+payWay);
				if(payWay==-1){Toast.makeText(ChoosePayAct.this, "请选择支付方式", Toast.LENGTH_SHORT).show();}
				if(payWay==HOUDOUPAY){
					Intent intent = new Intent(ChoosePayAct.this, HoudouPayAct.class);
					JSONObject payDuty= new JSONObject();
					payDuty.put("toWho", "订单"+orderJO.getLong(Order.ID));
					payDuty.put("money", orderJO.getDouble(Order.MONEYCU));
					intent.putExtra("payDuty", payDuty.toString());
					startActivityForResult(intent, HOUDOUPAY);
				}
			}
		};
		checkedListener= new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton v, boolean isChecked) {
				System.out.println("isChecked="+isChecked+"v.getId="+v.getId()  +" ckHoudou.getId()="+ckHoudou.getId()+"  ckAli.getId=+"+ckAli.getId()+"  ckTecent.ID="+ckTecent.getId());
				if(v==ckHoudou){
					if(isChecked){
						double moneyNotEnough=orderJO.getDouble(Order.MONEYCU)-Constant.customerJO.getDouble(Customer.MONEY);
						if(moneyNotEnough>0){
							deduct.setText("抵扣"+Constant.customerJO.getDouble(Customer.MONEY)+"元，剩余"+moneyNotEnough+"元"); 
							deduct.setVisibility(View.VISIBLE);
						}
						ckAli.setChecked(false);ckTecent.setChecked(false);
						payWay=HOUDOUPAY;
					}else{
						deduct.setVisibility(View.GONE);
						payWay=-1;
					}
				}
                if(v==ckAli){
                	if(isChecked){
                		
                	}else{
                		payWay=-1;
                	}
				}
                if(v==ckTecent){
                  if(isChecked){
                		
                	}else{
                		payWay=-1;	
                	}
				}
			}
		};
		
	}
	
	private   class HttpPostTaskforPayDo extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 lt_shadow.setVisibility(View.GONE);	
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 CommonFunction.alert(ChoosePayAct.this, "失败", "无网络连接");return;
		      
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
			    String affair="";
				JSONObject json = null;
				JSONObject orderJOOnline;
				JSONObject cutomerJOOnline;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				 affair= json.getString("affair");
				}catch(JSONException e){
					 CommonFunction.alert(ChoosePayAct.this, "失败", "数据解析错误");return;
				}
										   												      		       
		       if(!success){   CommonFunction.alert(ChoosePayAct.this, "失败", errorInfo);return; }
		       orderJOOnline=json.getJSONObject("order");
		      if(affair.equals(AFFAIR_ORDERPAID)){
			   if(orderJOOnline.getInt(Order.STATE)==10){
				   Toast.makeText(ChoosePayAct.this, "支付成功，即将跳转", Toast.LENGTH_SHORT).show();
				   Intent intent = new Intent(ACTION_ORDER_CHANGED);  
				   intent.putExtra("order", orderJOOnline.toString());  
				   sendBroadcast(intent);     
				   try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				   ChoosePayAct.this.finish();		 
			   }else if(orderJOOnline.getInt(Order.STATE)==3){
				   cutomerJOOnline=json.getJSONObject("customer");
				   Constant.customerJO.put(Customer.MONEY, cutomerJOOnline.getDouble(Customer.MONEY));
				   Builder b = new AlertDialog.Builder(ChoosePayAct.this).setTitle("提示")  
						     .setMessage("亲，我们非常遗憾的告诉您，虽然您的订单已经支付成功，但是支付已经超时15分钟，订单已被取消，我们已经退款到您的厚豆账户上。非常抱歉");  
						   b.setPositiveButton("确认", new DialogInterface.OnClickListener() {  
						    public void onClick(DialogInterface dialog, int whichButton) {  					    	
						    	 dialog.cancel();   ChoosePayAct.this.finish();
						    }  
						   }).show(); 			   
			   }
		      }
		      if(affair.equals(AFFAIR_DeProtect)){
		    	  Toast.makeText(ChoosePayAct.this, "解除支付保护成功", Toast.LENGTH_SHORT).show();
		    	  Intent intent = new Intent(ACTION_ORDER_CHANGED);  
				   intent.putExtra("order", orderJOOnline.toString());  
				   sendBroadcast(intent); 
		      }
		} //onPostExecute
	} //AsyncTask

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		// super.onActivityResult(requestCode, resultCode, data);
		  System.out.println("resultCode="+resultCode+"requestCode="+requestCode);
		if(requestCode==HOUDOUPAY){
			JSONObject result= JSONObject.fromObject(intent.getStringExtra("result"));
			if(result.getBoolean("success")){
				isPaySuccess=true;
				String[] params= new String[3];
	            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
	            params[1]=AFFAIR_ORDERPAID;
	            JSONObject currentOrderJO= new JSONObject();
	            currentOrderJO.put(Order.ID, orderJO.getLong(Order.ID));
	            JSONObject jsonData= new JSONObject();
	            jsonData.put("order", currentOrderJO);
	            jsonData.put("customer", Constant.customerJO);
	            jsonData.put("payWay", 1);
	            params[2]=jsonData.toString();
	            new HttpPostTaskforPayDo().execute(params);
			}else{
			//	Toast.makeText(ChoosePayAct.this, "厚豆支付失败"+result.getString("errorInfo"),Toast.LENGTH_SHORT).show();
			}
		}
		
	}	


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(!isPaySuccess){
			String[] params= new String[3];
	        params[0]=Constant.BaseUrl+Constant.CustomerUrl;
	        params[1]=AFFAIR_DeProtect;
	        JSONObject currentOrderJO= new JSONObject();
	        currentOrderJO.put(Order.ID, orderJO.getLong(Order.ID));
	        JSONObject jsonData= new JSONObject();
	        jsonData.put("order", currentOrderJO);
	        jsonData.put("customer", Constant.customerJO);
	        params[2]=jsonData.toString();
	        new HttpPostTaskforPayDo().execute(params);
	        }
		super.onDestroy();
	}
	
	
}
